package client

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"me/123/common/proto/product"
)

type ProductHandler func(ctx context.Context, in product.ProductsClient) (interface{}, error)

func ProductClient(ctx context.Context, handler ProductHandler) (interface{}, error) {
	conn, err := grpc.Dial("127.0.0.1:8081", grpc.WithInsecure())
	if err != nil {
		fmt.Printf("连接异常： %s\n", err)
		return nil, err
	}
	defer conn.Close()
	client := product.NewProductsClient(conn)
	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}
	return res, err
}

func ProductList(ctx context.Context, req *product.ProductListRequest) (*product.ProductListResponse, error) {
	client, err := ProductClient(ctx, func(ctx context.Context, in product.ProductsClient) (interface{}, error) {
		list, err := in.ProductList(ctx, req)
		if err != nil {
			return nil, err
		}
		return list, err
	})
	if err != nil {
		return nil, err
	}
	return client.(*product.ProductListResponse), nil
}

func List(ctx context.Context, req *product.ListRequest) (*product.ListResponse, error) {
	client, err := ProductClient(ctx, func(ctx context.Context, in product.ProductsClient) (interface{}, error) {
		list, err := in.List(ctx, req)
		if err != nil {
			return nil, err
		}
		return list, err
	})
	if err != nil {
		return nil, err
	}
	return client.(*product.ListResponse), nil
}

func UserList(ctx context.Context, req *product.UserListRequest) (*product.UserListResponse, error) {
	client, err := ProductClient(ctx, func(ctx context.Context, in product.ProductsClient) (interface{}, error) {
		list, err := in.UserList(ctx, req)
		if err != nil {
			return nil, err
		}
		return list, err
	})
	if err != nil {
		return nil, err
	}
	return client.(*product.UserListResponse), nil
}
